<?php

class ome_mdl_orders extends dbeav_model{
	var $has_tag = true;
    var $has_many = array(
       //'delivery' => 'delivery', TODO:非标准写法，去掉后有报错需要修改代码
       'order_objects' => 'order_objects',
    );

    var $defaultOrder = array('createtime DESC ,order_id DESC');

    function _filter($filter,$tableAlias=null,$baseWhere=null){
        $where = "1";
        if(isset($filter['order_confirm_filter'])){
            $where = $filter['order_confirm_filter'];
            unset($filter['order_confirm_filter']);
        }
        if (isset($filter['assigned']))
        {
            if ($filter['assigned'] == 'notassigned')
            {
                $where .= ' AND (`op_id` is null and `group_id` is null)';
            }
            else
            {
                $where .= '  AND (`op_id` is not null or `group_id` is not null)';
            }
            unset ($filter['assigned']);
        }
        if (isset($filter['balance'])){
            if ($filter['balance'])
                $where .= " AND `old_amount` != 0 AND `total_amount` != `old_amount` ";
            else
                $where .= " AND `old_amount` = 0 ";
        }
        //自动取消订单过滤条件
        if (isset($filter['auto_cancel_order_filter'])){
            $where .= '  AND '.$filter['auto_cancel_order_filter'];
        }

        if(isset($filter['product_bn'])){
            $itemsObj = &$this->app->model("order_items");
            $rows = $itemsObj->getOrderIdByPbn($filter['product_bn']);
            $orderId[] = 0;
            foreach($rows as $row){
                $orderId[] = $row['order_id'];
            }
            $where .= '  AND order_id IN ('.implode(',', $orderId).')';
            unset($filter['product_bn']);
        }

        //支付失败
        if(isset($filter['payment_fail']) && $filter['payment_fail'] == true){
            $api_fail = &$this->app->model("api_fail");
            $payment_fail_list = $api_fail->getList('order_id', array('type'=>'payment'), 0, -1);
            $payment_order_id = array();
            if ($payment_fail_list){
                foreach($payment_fail_list as $val){
                    $payment_order_id[] = $val['order_id'];
                }
            }
            $payment_order_id = implode(',', $payment_order_id);
            $payment_order_id =  $payment_order_id ? $payment_order_id : '\'\'';
            $where .= '  AND order_id IN ('.$payment_order_id.')';
            unset($filter['payment_fail']);
        }

        if(isset($filter['product_barcode'])){
            $itemsObj = &$this->app->model("order_items");
            $rows = $itemsObj->getOrderIdByPbarcode($filter['product_barcode']);
            $orderId[] = 0;
            foreach($rows as $row){
                $orderId[] = $row['order_id'];
            }
            $where .= '  AND order_id IN ('.implode(',', $orderId).')';
            unset($filter['product_barcode']);
        }
        //判断是否录入发票号
        if(isset($filter['is_tax_no'])){
            if($filter['is_tax_no']==1){
                $where .= '  AND tax_no IS NOT NULL';

            }else{
                $where .= '  AND tax_no IS NULL';
            }
            unset($filter['is_tax_no']);
        }
        //付款确认
        if (isset($filter['pay_confirm'])){
            $where .= ' AND '.$filter['pay_confirm'];
            unset($filter['pay_confirm']);
        }
        //确认状态
        if (isset($filter['process_status_noequal'])){
            $value = '';
            foreach($filter['process_status_noequal'] as $k=>$v){
                $value .= "'".$v."',";
            }
            $len = strlen($value);
            $value_last = substr($value,0,($len-1));
            $where .= ' AND process_status not in ( '.$value_last.")";
            unset($filter['process_status_noequal']);
        }
        if (isset($filter['member_uname'])){
            $memberObj = &$this->app->model("members");
            $rows = $memberObj->getList('member_id',array('uname|has'=>$filter['member_uname']));
            $memberId[] = 0;
            foreach($rows as $row){
                $memberId[] = $row['member_id'];
            }
            $where .= '  AND member_id IN ('.implode(',', $memberId).')';
            unset($filter['member_uname']);
        }
       // echo $where;
        if (isset($filter['pay_bn'])){
        	$cfgObj = &app::get('ome')->model('payment_cfg');
        	$rows = $cfgObj->dump(array('pay_bn'=>$filter['pay_bn']),'custom_name');
        	//var_dump($rows);
        	$where .= '  AND payment = \''.$rows['custom_name'].'\'';
        	unset($filter['pay_bn']);
        }else{
        	if (isset($filter['pay_type'])){
        		$cfgObj = &app::get('ome')->model('payment_cfg');
        		$rows = $cfgObj->getList('custom_name',array('pay_type'=>$filter['pay_type']));
        		$pay_bn[] = 0;
        		 
        		foreach($rows as $row){
        			$pay_bn[] = $row['custom_name'];
        		}
        		$where .= '  AND payment IN (\''.implode('\',\'', $pay_bn).'\')';

        		unset($filter['pay_type']);
        	}
         }
       // echo $where;
        if(isset($filter['ship_tel_mobile'])){
            $where .= ' AND (ship_tel=\''.$filter['ship_tel_mobile'].'\' or ship_mobile=\''.$filter['ship_tel_mobile'].'\')';
            unset($filter['ship_tel_mobile']);
        }
        //部分支付 包含部分退款 部分支付
        if(isset($filter['pay_status_part'])){
            $where .= ' AND (pay_status = \'3\' or (pay_status = \'4\' and ship_status = \'0\'))';
            unset($filter['pay_status_part']);
        }
        //付款确认时，部分退款的只有未发货的才能继续支付
        if(isset($filter['pay_status_set'])){
            if($filter['pay_status_set'] == 2){
                $where .= ' AND (pay_status in (\'0\',\'3\') or (pay_status = \'4\' and ship_status = \'0\'))';
            }else{
                $where .= ' AND (pay_status in (\'0\',\'3\',\'8\') or (pay_status = \'4\' and ship_status = \'0\'))';
            }
            unset($filter['pay_status_set']);
        }
        return parent::_filter($filter,$tableAlias,$baseWhere)." AND ".$where;
    }

    function modifier_mark_type($row){
        if($row){
            $tmp = ome_order_func::order_mark_type($row);
            if($tmp){
                $tmp = "<img src='".$tmp."' width='20' height='20'>";
                return $tmp;
            }
        }
    }

    /*
     * 订单暂停
     */
    function pauseOrder($order_id){
        if ($order_id){
            $o = $this->dump($order_id,'pause');
            if ($o['pause'] == 'false'){
                $dlyObj = &$this->app->model("delivery");
                $oOperation_log = &$this->app->model('operation_log');

                $order['order_id'] = $order_id;
                $order['pause'] = 'true';
                $this->save($order);
                $oOperation_log->write_log('order_modify@ome',$order_id,'订单暂停');
                $ids = $this->db->select("SELECT dord.delivery_id,d.pause,d.process FROM sdb_ome_delivery_order AS dord
                                            LEFT JOIN sdb_ome_delivery AS d ON(dord.delivery_id=d.delivery_id)
                                            WHERE dord.order_id={$order_id} AND d.disabled='false'");
                if ($ids)
                foreach ($ids as $dly){
                    if ($dly['pause'] == 'false' && $dly['process'] == 'false'){
                        $tmpdly = array(
                            'delivery_id' => $dly['delivery_id'],
                            'pause' => 'true'
                        );
                        $dlyObj->save($tmpdly);
                        $oOperation_log->write_log('delivery_modify@ome',$dly['delivery_id'],'发货单暂停');
                    }
                }
                //订单暂停状态同步
                if ($service_order = kernel::servicelist('service.order')){
                    foreach($service_order as $object=>$instance){
                        if(method_exists($instance, 'update_order_pause_status')){
                           $instance->update_order_pause_status($order_id);
                        }
                    }
                }
                return true;
            }
        }
        return false;
    }

    /*
     * 订单恢复
     */
    function renewOrder($order_id){
        if ($order_id){
            $o = $this->dump($order_id,'pause');
            if ($o['pause'] == 'true'){
                $dlyObj = &$this->app->model("delivery");
                $oOperation_log = &$this->app->model('operation_log');

                $order['order_id'] = $order_id;
                $order['pause'] = 'false';
                $this->save($order);
                $oOperation_log->write_log('order_modify@ome',$order_id,'订单恢复');
                $ids = $this->db->select("SELECT dord.delivery_id,d.pause,d.process FROM sdb_ome_delivery_order AS dord
                                            LEFT JOIN sdb_ome_delivery AS d ON(dord.delivery_id=d.delivery_id)
                                            WHERE dord.order_id={$order_id} AND d.disabled='false'");
                if ($ids)
                foreach ($ids as $dly){
                    if ($dly['pause'] == 'true' && $dly['process'] == 'false'){
                        $tmpdly = array(
                            'delivery_id' => $dly['delivery_id'],
                            'pause' => 'false'
                        );
                        $dlyObj->save($tmpdly);
                        $oOperation_log->write_log('delivery_modify@ome',$dly['delivery_id'],'发货单恢复');
                    }
                }
                //订单恢复状态同步
                if ($service_order = kernel::servicelist('service.order')){
                    foreach($service_order as $object=>$instance){
                        if(method_exists($instance, 'update_order_pause_status')){
                           $instance->update_order_pause_status($order_id, 'false');
                        }
                    }
                }
                return true;
            }
        }
        return false;
    }

    //分派时间
    function modifier_dispatch_time($row){
       if ($row){
           $tmp = date('Y年m月d日 H点',$row);
           return $tmp;
       }
    }

    /**
     * 打回订单的发货单
     * @param int $order_id 订单号
     * @param boolean $reback_status 打回状态，默认为false:打回所有发货单;true：只打回未发货的发货单
     */
    function rebackDeliveryByOrderId($order_id,$dly_status=false){
        $dlyObj = &$this->app->model("delivery");
        $dly_oObj = &$this->app->model("delivery_order");
        $opObj = &$this->app->model('operation_log');
        $data = $dly_oObj->getList('*',array('order_id'=>$order_id),0,-1);
        $bind = array();
        $dlyos = array();
        $mergedly = array();
        if ($data)
        foreach ($data as $v){
            $dly = $dlyObj->dump($v['delivery_id']);
            //只打回未发货的发货单
            if ($dly_status == true){
                if ($dly['process'] == 'true') continue;
            }
            if ($dly['parent_id'] == 0 && $dly['is_bind'] == 'true'){
                $bind[$v['delivery_id']]['delivery_id'] = $v['delivery_id'];
            }elseif ($dly['parent_id'] == 0){
                $dlyos[$v['delivery_id']][] = $v['delivery_id'];
            }else{
                $mergedly[$v['delivery_id']] = $v['delivery_id'];
                $bind[$dly['parent_id']]['items'][] = $v['delivery_id'];
            }
        }

        if ($bind)
        foreach ($bind as $k => $i){
            $items = $dlyObj->getItemsByParentId($i['delivery_id'], 'array', 'delivery_id');
            if (sizeof($items) - sizeof($i['items']) < 2){
                $result = $dlyObj->splitDelivery($i['delivery_id']);
            }else {
                $result = $dlyObj->splitDelivery($i['delivery_id'], $i['items']);
            }
            if ($result){
                $dlyObj->rebackDelivery($i['items'], '', $dly_status);
                foreach ($i['items'] as $i){
                    $opObj->write_log('delivery_back@ome', $i ,'发货单打回');
                    $dlyObj->updateOrderPrintFinish($i, 1);
                }
            }
        }

        if ($dlyos)
        foreach ($dlyos as $v){
            $dlyObj->rebackDelivery($v, '', $dly_status);
            $opObj->write_log('delivery_back@ome', $v ,'发货单打回');
            $dlyObj->updateOrderPrintFinish($v, 1);
        }
        return true;
    }

    /**
     * 获得总数量
     *
     * @param string $where
     *
     * @return array()
     */
    function get_all($where){
        $minute = $this->app->getConf('ome.order.unconfirmtime');
        $time = time() - $minute*60;

        $sql = "SELECT COUNT(o.order_id) AS 'TOTAL' FROM sdb_ome_orders o
                                        WHERE 1 $where ";
        $re4 = $this->db->selectrow($sql);
        $sql = "SELECT COUNT(o.order_id) AS 'TOTAL' FROM sdb_ome_orders o
                                        WHERE (is_cod='true' OR pay_status='1') $where
                                            AND (`op_id` is null and `group_id` is null)";
        $re1 = $this->db->selectrow($sql);
        $sql = "SELECT COUNT(o.order_id) AS 'TOTAL' FROM sdb_ome_orders o
                                        WHERE (`op_id` is not null or `group_id` is not null) $where
                                            AND o.confirm='N'";
        $re2 = $this->db->selectrow($sql);
        $sql = "SELECT COUNT(o.order_id) AS 'TOTAL' FROM sdb_ome_orders o
                                        WHERE (`op_id` is not null or `group_id` is not null) $where
                                            AND o.confirm='N'
                                            AND o.dt_begin < $time ";
        $re3 = $this->db->selectrow($sql);

        $re['all'] = $re4['TOTAL'];
        $re['a'] = $re1['TOTAL'];
        $re['b'] = $re2['TOTAL'];
        $re['c'] = $re3['TOTAL'];
        return $re;
    }


    /**
     * 获得确认组订单数量
     *
     * @param string $where
     *
     * @return array
     */
    function get_group($where){
        $sql = "SELECT o.group_id,g.name FROM sdb_ome_orders o
                                JOIN sdb_ome_groups g
                                    ON o.group_id=g.group_id
                                WHERE g.g_type='confirm' $where GROUP BY o.group_id ";
        $data = $this->db->select($sql);
        $result = array();
        if ($data){
            $minute = $this->app->getConf('ome.order.unconfirmtime');
            $time = time() - $minute*60;
            foreach ($data as $v){
                $group_id = $v['group_id'];
                $result[$group_id]['name'] = $v['name'];

                $sql = "SELECT COUNT(order_id) AS 'TOTAL' FROM sdb_ome_orders  as o
                                        WHERE group_id=$group_id
                                            AND (`op_id` is not null or `group_id` is not null)
                                            AND confirm='N' $where";
                $re = $this->db->selectrow($sql);
                $result[$group_id]['b'] = $re['TOTAL'];

                $sql = "SELECT COUNT(order_id) AS 'TOTAL' FROM sdb_ome_orders
                                        WHERE group_id=$group_id
                                            AND (`op_id` is not null or `group_id` is not null)
                                            AND confirm='N'
                                            AND dt_begin < $time ";
                $re = $this->db->selectrow($sql);
                $result[$group_id]['c'] = $re['TOTAL'];
            }
        }

        return $result;
    }


    /**
     * 获得已分派但未确认时间超过设定时间的订单数量
     *
     * @param string $where
     * @param string $type
     *
     * @return number
     */
    function get_operator($where){
        $sql = "SELECT o.group_id,g.name as 'g_name',o.op_id,u.name as 'u_name' FROM sdb_ome_orders o
                                JOIN sdb_ome_groups g
                                    ON o.group_id=g.group_id
                                JOIN sdb_desktop_users u
                                    ON u.user_id=o.op_id
                                WHERE g.g_type='confirm' $where GROUP BY o.op_id ";
        $data = $this->db->select($sql);
        $result = array();
        if ($data){
            $minute = $this->app->getConf('ome.order.unconfirmtime');
            $time = time() - $minute*60;
            foreach ($data as $v){
                $op_id = $v['op_id'];
                $result[$op_id]['g_name'] = $v['g_name'];
                $result[$op_id]['u_name'] = $v['u_name'];

                $sql = "SELECT COUNT(order_id) AS 'TOTAL' FROM sdb_ome_orders as o
                                        WHERE op_id=$op_id
                                            AND (`op_id` is not null or `group_id` is not null)
                                            AND confirm='N' $where";
                $re = $this->db->selectrow($sql);
                $result[$op_id]['b'] = $re['TOTAL'];

                $sql = "SELECT COUNT(order_id) AS 'TOTAL' FROM sdb_ome_orders
                                        WHERE op_id=$op_id
                                            AND (`op_id` is not null or `group_id` is not null)
                                            AND confirm='N'
                                            AND dt_begin < $time ";
                $re = $this->db->selectrow($sql);
                $result[$op_id]['c'] = $re['TOTAL'];
            }
        }

        return $result;
    }

    function get_confirm_ops(){
        $sql = "SELECT go.op_id,u.name FROM sdb_ome_group_ops go
                            JOIN sdb_ome_groups g
                                ON g.group_id = go.group_id
                            JOIN sdb_desktop_users u
                                ON go.op_id = u.user_id
                            WHERE g.g_type = 'confirm' GROUP BY go.op_id ";
        $re = $this->db->select($sql);
        return $re;
    }
    /*
     * 根据订单来恢复预占的冻结库存
     * 比如在订单被取消时，就需要恢复冻结库存
     *
     * @param int $order_id
     *
     */
    function unfreez($order_id){
        $delivery_ids = $this->db->select("SELECT dord.delivery_id FROM sdb_ome_delivery_order AS dord
                                            LEFT JOIN sdb_ome_delivery AS d ON(dord.delivery_id=d.delivery_id)
                                            WHERE dord.order_id={$order_id} AND d.is_bind='false' AND d.disabled='false'");

        $oDelivery = &$this->app->model("delivery");
        if($delivery_ids){
            foreach($delivery_ids as $v){
                $oDelivery->unfreez($v['delivery_id']);
            }
        }

        //unfreeze剩余未生成发货单的货品
        $items = $this->db->select("SELECT product_id,nums FROM sdb_ome_order_items WHERE order_id=".$order_id);
        $oProduct = &$this->app->model("products");
        foreach($items as $v){
            $num = $v['nums'] - $oDelivery->getDeliveryFreez($order_id,$v['product_id']);
            $oProduct->chg_product_store_freeze($v['product_id'],$num,"-");
        }

        return true;
    }

    /**
     * 更新订单状态
     *
     * @param bigint $order_id
     * @param string $status
     *
     * @return boolean
     */
    function set_status($order_id, $status){
        $data['order_id'] = $order_id;
        $data['process_status']   = $status;


        return $this->save($data);
    }

    /*
     * 取消发货单
     *
     * @param int $order_id
     *
     * @return bool
     */
    function cancel_delivery($order_id){
        $delivery_ids = $this->db->select("SELECT dord.delivery_id,d.is_bind,d.status FROM sdb_ome_delivery_order AS dord
                                            LEFT JOIN sdb_ome_delivery AS d ON(dord.delivery_id=d.delivery_id)
                                            WHERE dord.order_id={$order_id} AND d.disabled='false'");
        if($delivery_ids){
            $oDelivery = &$this->app->model("delivery");
            $delivery_itemsObj = &$this->app->model('delivery_items');
            $branch_productObj = $this->app->model('branch_product');
            foreach($delivery_ids as $v){
                //增加释放branch_product的冻结库存
                $branch_id = $oDelivery->getList('branch_id',array('delivery_id'=>$v['delivery_id']),0,-1);
                $branch_id = $branch_id['0']['branch_id'];
                $items = $delivery_itemsObj->getList('product_id,number',array('delivery_id'=>$v['delivery_id']),0,-1);
                //取消的，打回的，发货的不释放冻结库存
                if($v['status']!='cancel' && $v['status']!='back' && $v['status'] != 'succ'){
                    foreach($items as $k=>$value){
                        $branch_productObj->unfreez($branch_id,$value['product_id'],$value['number']);
                    }
                }

                if ($v['status'] != 'succ'){
                    //更新发货单状态 API
                    foreach(kernel::servicelist('service.delivery') as $object=>$instance){
                        if(method_exists($instance,'update_status')){
                            $instance->update_status($v['delivery_id'], 'cancel', false);
                        }
                    }
                    $oDelivery->set_status($v['delivery_id'],'cancel');
                }
                if ($v['is_bind'] == 'true'){
                    $oDelivery->splitDelivery($v['delivery_id']);
                }
            }
        }
    }

    function order_detail($order_id){
        $order_detail = $this->dump($order_id);
        return $order_detail;
    }
    /*
     * 设置订单异常，并保存异常类型和备注
     *
     * @param array $data abnormal对象的sdf结构数据
     * @param string $log_memo 日志备注
     *
     */
    function set_abnormal($data){
        //组织 分派的数组 $data_dispatch 跟filter(跟dispatch 的参数形式保持一致)
        $data_dispatch = array(
            'group_id' =>$data['group_id'],
            'op_id' =>$data['op_id'],
            'dt_begin' =>time(),
            'dispatch_time' =>time(),
        );
        //组织 set_abnormal的数组
        $data = array(
            'abnormal_id'=>$data['abnormal_id'],
            'order_id'=>$data['order_id'],
            'is_done'=>$data['is_done'],
            'abnormal_memo'=>$data['abnormal_memo'],
        );
        $memo = "";
        $oAbnormal = &$this->app->model('abnormal');

        //备注信息
        $oldmemo = $oAbnormal->dump(array('abnormal_id'=>$data['abnormal_id']), 'abnormal_memo');
        $oldmemo= unserialize($oldmemo['abnormal_memo']);
        if ($oldmemo)
        foreach($oldmemo as $k=>$v){
            $memo[] = $v;
        }
        $op_name = kernel::single('desktop_user')->get_name();
        $newmemo =  htmlspecialchars($data['abnormal_memo']);
        $memo[] = array('op_name'=>$op_name, 'op_time'=>date('Y-m-d H:i',time()), 'op_content'=>$newmemo);
        $data['abnormal_memo'] = serialize($memo);
        $oAbnormal->save($data);

        switch ($data['is_done']){
            case 'false':
                $order_data = array('order_id'=>$data['order_id'],'abnormal'=>'true');
                $this->save($order_data);
                $memo = "设置订单异常";
                break;
            case 'true' :
                $orderObj = &app::get('ome')->model('orders');
                $order = $orderObj->dump($data['order_id']);
                if ($order['ship_status'] == 2){
                    $filter = array(
                        'order_id'=>$data['order_id'],
                        'abnormal'=>'false',
                        'confirm'=>'Y',
                        'process_status'=>'splitting',
                        'dispatch_time'=>0,
                        'print_finish'=>'false'
                    );
                }elseif ($order['process_status'] == 'cancel'){
                    $filter = array(
                        'order_id'=>$data['order_id'],
                        'abnormal'=>'false',
                        'confirm'=>'N',
                        'group_id'=>NULL,
                        'op_id'=>NULL,
                        'dispatch_time'=>0,
                        'print_finish'=>'false'
                    );
                }else {
                    $filter = array(
                        'order_id'=>$data['order_id'],
                        'abnormal'=>'false',
                        'confirm'=>'N',
                        'process_status'=>'unconfirmed',
                        'group_id'=>NULL,
                        'op_id'=>NULL,
                        'dispatch_time'=>0,
                        'print_finish'=>'false'
                    );
                }
                $order_data = $filter;
                $this->save($order_data);

                $memo = "修改订单异常备注";
                break;
        }

        //写操作日志
        $oOperation_log = &$this->app->model('operation_log');
        $oOperation_log->write_log('order_modify@ome',$data['order_id'],$memo);
    }

    /*
     * 获取订单明细列表
     *
     * @param int $order_id 订单id
     * @param bool $sort 是否要排序，默认不要。排序后的结果会按照普通商品、捆绑商品、赠品、配件等排列
     *
     * @return array
     */
    function getItemList($order_id,$sort=false){
        $order_items = array();

        if($sort){
            $items = $this->dump($order_id,"order_id",array("order_objects"=>array("*")));
            foreach($items['order_objects'] as $k=>$v){
                $order_items[$v['obj_type']][$k] = $v;
                foreach($this->db->select("SELECT *,nums AS quantity FROM sdb_ome_order_items WHERE obj_id=".$v['obj_id']." AND item_type='product' ORDER BY item_type") as $it){
                    $order_items[$v['obj_type']][$k]['order_items'][$it['item_id']] = $it;
                }
                foreach($this->db->select("SELECT *,nums AS quantity FROM sdb_ome_order_items WHERE obj_id=".$v['obj_id']." AND item_type<>'product' ORDER BY item_type") as $it){
                    $order_items[$v['obj_type']][$k]['order_items'][$it['item_id']] = $it;
                }
            }

        }else{
            $items = $this->dump($order_id,"order_id",array("order_objects"=>array("*",array("order_items"=>array("*")))));
            foreach($items['order_objects'] as $oneobj)
            {
                foreach ($oneobj['order_items'] as $objitems)
                $order_items[] = $objitems;
            }
        }
        return $order_items;
    }

    /*
     * 获取订单明细以及明细商品在各个仓库中的库存
     *
     * @param int $order_id
     *
     * @return array
     */
    function getItemBranchStore($order_id){
        $order_items = $this->getItemList($order_id,true);
        $oProduct = &$this->app->model("products");
        $tmp = array();
        if($order_items){
            $oDelivery = &$this->app->model("delivery");
            foreach($order_items as $obj_type=>$object_type){
                foreach($object_type as $obj_id=>$obj){
                    foreach($obj['order_items'] as $k=>$item){
                        $order_items[$obj_type][$obj_id]['order_items'][$k]['branch_store'] = $oProduct->get_branch_store($item['product_id']);
                        $sql = "SELECT SUM(number) AS 'num' FROM `sdb_ome_delivery_items_detail` did
                                                    JOIN `sdb_ome_delivery` d
                                                        ON d.delivery_id=did.delivery_id
                                                    WHERE order_item_id='".$item['item_id']."'
                                                        AND product_id='".$item['product_id']."'
                                                        AND d.status != 'back'
                                                        AND d.status != 'cancel'
                                                        AND d.is_bind = 'false'";
                        $oi = $this->db->selectrow($sql);
                        if ($item['quantity'] <= intval($oi['num'])){
                            $order_items[$obj_type][$obj_id]['order_items'][$k]['left_nums'] = 0;
                            if ($obj_type == 'pkg'){
                                $order_items[$obj_type][$obj_id]['left_nums'] = 0;
                            }elseif ($obj_type == 'giftpackage'){
                                $order_items[$obj_type][$obj_id]['left_nums'] = 0;
                            }
                        }else {
                            $tmp_num = $item['quantity']-intval($oi['num']);
                            $order_items[$obj_type][$obj_id]['order_items'][$k]['left_nums'] = $tmp_num;
                            if ($obj_type == 'pkg'){
                                $order_items[$obj_type][$obj_id]['left_nums'] = intval($obj['quantity'] / $item['quantity'] * $tmp_num);
                            }elseif ($obj_type == 'giftpackage'){
                                $order_items[$obj_type][$obj_id]['left_nums'] = intval($obj['quantity'] / $item['quantity'] * $tmp_num);
                            }
                        }
                    }
                }
            }
        }

        return $order_items;
    }

    function getItemsNum($order_id, $product_id){
        $sql = "SELECT SUM(nums) AS '_count' FROM sdb_ome_order_items WHERE order_id='".$order_id."' AND product_id='".$product_id."'";
        $row = $this->db->selectrow($sql);
        return $row['_count'];
    }

    /*
     * 获取本订单的order_object的对象别名
     *
     * @param bigint $order_id
     *
     * @return array
     */
    function getOrderObjectAlias($order_id){
        $ret = array();
        $order_object = $this->db->select("SELECT DISTINCT(obj_type),obj_alias FROM sdb_ome_order_objects WHERE order_id={$order_id} ORDER BY obj_type");
        foreach($order_object as $v){
            $ret[$v['obj_type']] = $v['obj_alias'];
        }

        return $ret;
    }

    /*
     * 获取订单商品可能会使用到的仓库
     *
     * @param int $order_id
     *
     * @return array
     */
    function getBranchByOrder($order_id){
        $branch = $this->db->select("SELECT distinct(b.branch_id),b.name,b.uname,b.phone,b.mobile,b.stock_threshold,b.weight FROM sdb_ome_branch AS b
                                           LEFT JOIN sdb_ome_branch_product AS bp ON(b.branch_id=bp.branch_id)
                                           LEFT JOIN sdb_ome_order_items AS oi ON(bp.product_id=oi.product_id)
                                           WHERE b.disabled='false' AND oi.order_id={$order_id} ORDER BY b.branch_id");

        return $branch;
    }

     /*
     * 生成订单号
     */
     function gen_id()
    {
        $i = rand(0,9999);
        do{
            if(9999==$i){
                $i=0;
            }
            $i++;
            $order_bn = date('YmdH').'10'.str_pad($i,6,'0',STR_PAD_LEFT);
            $row = $this->db->selectrow('SELECT order_id from sdb_ome_orders where order_bn ='.$order_bn);
        }while($row);
        return $order_bn;
    }

    /*
     * 订单确认操作
     *
     * @param bigint $order_id 订单id
     * @param array $ship_info 收货人信息
     *
     * @return bool
     */
    function confirm($order_id,$is_auto=false){
        if($order=$this->dump($order_id,"*")){
            if($order['confirm']=='Y' || $order['process_status'] == 'cancel'){
                return false;
            }
        }

        $data['order_id'] = $order_id;
        $data['process_status'] = 'confirmed';
        $data['confirm'] = 'Y';
        $data['is_auto'] = $is_auto;

        $this->save($data);
        $oOperation_log = &$this->app->model('operation_log');
        $opinfo = NULL;
        if ($is_auto) $opinfo = kernel::single('ome_func')->get_system();
        $oOperation_log->write_log('order_confirm@ome',$data['order_id'],"订单确认",NULL,$opinfo);

        //订单确认状态同步
        if ($service_order = kernel::servicelist('service.order')){
        	foreach($service_order as $object=>$instance){
        		if(method_exists($instance, 'update_order_status')){
        			$instance->update_order_status($order_id,'confirmed','订单确认');
        		}
        	}
        }
        return true;
    }

    /*
     * 拆分订单，生成发货单
     *
     * @param bigint $order_id
     */
    function mkDelivery($order_id,$delivery_info){
        $oDelivery = &$this->app->model("delivery");
        $dly_orderObj =  &$this->app->model("delivery_order");
        $delivery_itemObj = &$this->app->model("delivery_items");
        $order_itemObj = &$this->app->model("order_items");
        if(is_array($delivery_info) && count($delivery_info)>0){
            $ids = array();
            foreach($delivery_info as $delivery){
                $tmp_items = $delivery['order_items'];
                unset($delivery['order_items']);
                $ids[] = $oDelivery->addDelivery($order_id,$delivery,array(),$tmp_items);
            }
            //根据orderid找到delivery
            $dly_orderdata = $dly_orderObj->getList("*",array("order_id"=>$order_id));
            $dlyitemcount = 0;
            foreach ($dly_orderdata as $dly_order){
                $sql = "SELECT SUM(di.number) AS 'total' FROM sdb_ome_delivery_items di
                                        JOIN sdb_ome_delivery d
                                            ON di.delivery_id=d.delivery_id
                                        WHERE d.delivery_id ='".$dly_order['delivery_id']."'
                                        AND d.status != 'back'
                                        AND d.status != 'cancel'
                                        AND d.disabled = 'false'
                                        AND d.is_bind = 'false'";

                $row = $this->db->selectrow($sql);
                $dlyitemcount += empty($row)?0:$row['total'];
            }
            $orderitemcount = 0;
            $orderitems = $order_itemObj->getList("*",array("order_id"=>$order_id));
            foreach ($orderitems as $oneitem){
                if ($oneitem['delete'] == 'false') $orderitemcount += $oneitem['nums'];
            }
            //如果delivery_item数量与order_item数量相等，则拆分完，否则部分拆分
            if ($orderitemcount <= $dlyitemcount)
            {
                $data['order_id'] = $order_id;
                $data['process_status'] = 'splited';
                $this->save($data);
            }
            else
            {
                $data['order_id'] = $order_id;
                $data['process_status'] = 'splitting';
                $this->save($data);
            }
            $oOperation_log = &$this->app->model('operation_log');
            $oOperation_log->write_log('order_split@ome',$data['order_id'],"订单拆分");
            return $ids;
        }
    }

     /*根据过滤条件查询数据*/
     function getOrderId($finderResult){
        $where = $finderResult? $this->_filter($finderResult):'order_id in ('.implode(',',$finderResult['order_id']).')';
        $sql = 'select order_id  from  sdb_ome_orders   where '.$where;
        return $this->db->select($sql);
     }

     /*
      * 订单详情查询
      * @param order_bn string
      * @return array
      */
     function getOrderBybn($filter=null, $cols='*', $lim=0, $limit=1){
       $sql = 'select '.$cols.' FROM `sdb_ome_orders` WHERE 1 ';
       if ($filter) $sql .= " AND ".$filter;
       $sql .= " limit $lim,$limit ";
       return $this->db->select($sql);
     }

    /*
     * 获取订单上下条
     * getOrderUpNext
     */
    function getOrderUpNext($id=null,$filter=null, $type='>'){
        if (!$id) return;
        $sql = "SELECT order_id,order_bn FROM `sdb_ome_orders` WHERE order_id $type '$id' ";
        $sql .= $filter;
        if ($type=='<') $desc = "desc";
        $sql .= " ORDER BY order_id $desc ";
        $tmp = $this->db->selectRow($sql);
        return $tmp;
    }

    /* create_order 订单创建
     * @param sdf $sdf
     * @return sdf
     */
    function create_order(&$sdf){

        //收货人/发货人地区转换
        $area = $sdf['consignee']['area'];
        kernel::single("ome_func")->region_validate($area);
        $sdf['consignee']['area'] = $area;
        $consigner_area = $sdf['consigner']['area'];
        kernel::single("ome_func")->region_validate($consigner_area);
        $sdf['consigner']['area'] = $consigner_area;

        $oProducts = &$this->app->model('products');

        //如果有OME捆绑插件设定的捆绑商品，则自动拆分
        if($oPkg = kernel::service('omepkg_order_split')){
            if(method_exists($oPkg,'order_split')){
                $sdf = $oPkg->order_split($sdf);
            }
        }

        //去除货号空格
         foreach($sdf['order_objects'] as $key=>$object){
        	$object['bn'] = trim($object['bn']);
            foreach($object['order_items'] as $k=>$item){
            	$item['bn'] = trim($item['bn']);
            	$object['order_items'][$k] = $item;
            }
            $sdf['order_objects'][$key] = $object;
         }
         
        foreach($sdf['order_objects'] as $key=>$object){
            foreach($object['order_items'] as $k=>$item){
                //货品属性
                $product_attr = array();
                $product_attr = $this->_format_productattr($item['product_attr'], $item['product_id']);
                $sdf['order_objects'][$key]['order_items'][$k]['addon'] = $product_attr;
                //修改预占库存
                $oProducts->chg_product_store_freeze($item['product_id'],(intval($item['quantity'])-intval($item['sendnum'])),"+");
            }
        }

        //注册service来对订单结构数据进行扩充和修改
        if($order_sdf_service = kernel::service('ome.service.order.sdfdata')){
            if(method_exists($order_sdf_service,'modify_sdfdata')){
                $sdf = $order_sdf_service->modify_sdfdata($sdf);
            }
        }

       if(!$this->save($sdf)) return false;

        //创建订单后执行的操作
        if($oServiceOrder = kernel::servicelist('ome_create_order_after')){
			  foreach($oServiceOrder as $object){
			      if(method_exists($object,'create_order_after')){
                      $object->create_order_after($sdf);
             	  }
			 }
        }

        //如果有KPI考核插件，会增加客服的考核
        if($oKpi = kernel::service('omekpi_servicer_incremental')){
            if(method_exists($oKpi,'getOrderIncremental')){
                $oKpi->getOrderIncremental($sdf);
            }
        }

        //订单创建api
        foreach(kernel::servicelist('service.order') as $object){
            if(method_exists($object, 'create_order')){
                $object->create_order($sdf);
            }
        }
		return true;
    }

    /**
     * 将前端店铺过来的货品规格属性值序列化
     * @access private
     * @param array $productattr 货品属性值
     * @return serialize 货品属性值
     */
    private function _format_productattr($productattr='',$product_id=''){
        if (!is_array($productattr) || empty($productattr)){
            $oSpecvalue = &$this->app->model('spec_values');
            $oSpec = &$this->app->model('specification');
            $oProducts = &$this->app->model('products');
            $productattr = array();
            $product_info = $oProducts->dump(array('product_id'=>$product_id),"spec_desc");
            $spec_desc = $product_info['spec_desc'];
            if ($spec_desc['spec_value_id'])
            foreach ($spec_desc['spec_value_id'] as $sk=>$sv){
                $tmp = array();
                $specval = $oSpecvalue->dump($sv,"spec_value,spec_id");
                $tmp['value'] = $specval['spec_value'];
                $spec = $oSpec->dump($specval['spec_id'],"spec_name");
                $tmp['label'] = $spec['spec_name'];
                $productattr[] = $tmp;
            }
        }
        $addon['product_attr'] = $productattr;
        return serialize($addon);
    }


     function save(&$data,$mustUpdate = null){
         //外键 先执行save
        $this->_save_parent($data,$mustUpdate);
        $plainData = $this->sdf_to_plain($data);
        if(!$this->db_save($plainData,$mustUpdate )) return false;

        $order_id = $plainData['order_id'];
        if(isset($data['order_objects'])){
            foreach($data['order_objects'] as $k=>$v){
                if(isset($v['order_items'])){
                    foreach($v['order_items'] as $k2=>$item){
                        $data['order_objects'][$k]['order_items'][$k2]['order_id'] = $order_id;
                    }
                }else{
                    break;
                }
            }
        }

        if( !is_array($this->idColumn) ){
            $data[$this->idColumn] = $plainData[$this->idColumn];
            $this->_save_depends($data,$mustUpdate );
        }
        $plainData = null; //内存用完就放
        return true;
     }

     function cancel($order_id,$memo,$isapi=true){
        $oOrder = &$this->app->model('orders');
        $oOperation_log = &$this->app->model('operation_log');

        $savedata = array();
        $savedata['order_id'] = $order_id;
        $savedata['process_status'] = 'cancel';
        $savedata['status'] = 'dead';
        $oOrder->save($savedata);

        //TODO: 订单取消作为单独的日志记录
        $oOrder->unfreez($order_id);
        $oOrder->cancel_delivery($order_id);
        $oOperation_log->write_log('order_modify@ome',$order_id,$memo);

        //2012- 10-30 刘向峰 增加isapi参数 如果是false则不往商城同步
        if($isapi){
        //订单取消 API
        foreach(kernel::servicelist('service.order') as $object=>$instance){
            if(method_exists($instance, 'update_order_status')){
                $instance->update_order_status($order_id, '', $memo);
            }
        }
        }

     }


    function searchOptions(){
        $parentOptions = parent::searchOptions();
        $childOptions = array(
            'product_bn'=>app::get('base')->_('货号'),
            'product_barcode'=>app::get('base')->_('条形码'),
            'member_uname'=>app::get('base')->_('用户名'),
        );
        return $Options = array_merge($parentOptions,$childOptions);
    }

    /*
     * $order_ids id数组
     */
    function dispatch($data,$filter,$order_ids,$is_auto=false){
		$data['is_auto'] = 'false';//手动分派，改变自动处理标示
        if(empty($data['op_id'])){
            $data['op_id'] = NULL;
        }
        $this->update($data,$filter);
        //写日志
        $oOperation_log = &$this->app->model('operation_log');
        $oGroup = &$this->app->model('groups');
        $oOperator = &app::get('desktop')->model('users');
        $memo = "";

        if($data['group_id']){
            $group = $oGroup->dump(intval($data['group_id']));
            $memo = '订单分派给'.$group['name'];

            if($data['op_id']){
                $operator = $oOperator->dump(intval($data['op_id']));
                $memo .= '的'.$operator['name'];
            }
        }else{
            $memo = "订单撤销分派";
        }

        if($order_ids[0] == '_ALL_'){
            $opinfo = NULL;
            if ($is_auto) $opinfo = kernel::single('ome_func')->get_system();
            $oOperation_log->batch_write_log('order_dispatch@ome',$memo,time(),$filter,$opinfo);
        }else{
            foreach($order_ids as $order_id){
                $opinfo = NULL;
                if ($is_auto){
                    $opinfo = kernel::single('ome_func')->get_system();
                }
                $oOperation_log->write_log('order_dispatch@ome',$order_id,$memo,NULL,$opinfo);
            }
        }


 		//创建订单后执行的操作
        if($data['group_id'] && $oServiceOrder = kernel::servicelist('ome_dispatch_after')){
            if($order_ids[0] == '_ALL_'){
                $order_ids = array();
                $rows = $this->getList("order_id",$filter,0,-1);
                foreach($rows as $v){
                    $order_ids[] = $v['order_id'];
                }
            }
            foreach($order_ids as $v){
				 foreach($oServiceOrder as $object){
			        if(method_exists($object,'dispatch_after')){
                        $object->dispatch_after($v);
             	    }
			 	}
            }
        }
        return true;
    }



    function exportTemplate($filter){
        foreach ($this->io_title($filter) as $v){
            $title[] = kernel::single('base_charset')->utf2local($v);
        }
        return $title;
    }

     function io_title( $filter=null,$ioType='csv' ){
        switch( $ioType ){
            case 'csv':
            default:
                $this->oSchema['csv']['order'] = array(
                    '*:订单号' => 'order_bn',
                    '*:支付方式' => 'payinfo/pay_name',
                    '*:下单时间' => 'createtime',
                    '*:配送方式' => 'shipping/shipping_name',
                    '*:配送费用' => 'shipping/cost_shipping',
                    '*:来源店铺编号' => 'shop_id',
                    '*:订单附言' => 'custom_mark',
                    '*:收货人姓名' => 'consignee/name',
                    '*:收货地址省份' => 'consignee/area/province',
                    '*:收货地址城市' => 'consignee/area/city',
                    '*:收货地址区/县' => 'consignee/area/county',
                    '*:收货详细地址' => 'consignee/addr',
                    '*:收货人固定电话' => 'consignee/telephone',
                    '*:电子邮箱' => 'consignee/email',
                    '*:收货人移动电话' => 'consignee/mobile',
                    '*:邮编' => 'consignee/zip',
                    '*:货到付款' => 'shipping/is_cod',
                    '*:是否开发票' => 'is_tax',
                    '*:发票抬头' => 'tax_title',
                    '*:发票金额' => 'cost_tax',
                    '*:优惠方案' => 'order_pmt',
                    '*:订单优惠金额' => 'pmt_order',
                    '*:商品优惠金额' => 'pmt_goods',
                    '*:折扣' => 'discount',
                    '*:返点积分' => 'score_g',
                    '*:商品总额' => 'cost_item',
                    '*:订单总额' => 'total_amount',
                );
                $this->oSchema['csv']['obj'] = array(
                    '*:订单号' => '',
                    '*:商品货号' => '',
                    '*:商品名称' => '',
                    '*:购买单位' => '',
                    '*:商品规格' => '',
                    '*:购买数量' => '',
                    '*:商品价格' => '',
                );
                break;
        }
        $this->ioTitle[$ioType]['order'] = array_keys( $this->oSchema[$ioType]['order'] );
        $this->ioTitle[$ioType]['obj'] = array_keys( $this->oSchema[$ioType]['obj'] );
        return $this->ioTitle[$ioType][$filter];
     }
     //csv导出
     function fgetlist_csv( &$data,$filter,$offset,$exportType = 1 ){
        set_time_limit(60*30); // 30分钟
        $max_offset = 100; // 最多一次导出100页
        if ($offset>$max_offset) return false;// 限制导出的最大页码数
        
        //return false;
		@ini_set('memory_limit','64M');
        if( !$data['title']['order'] ){
            $title = array();
            foreach( $this->io_title('order') as $k => $v ){
                $title[] = $this->charset->utf2local($v);
            }
            $data['title']['order'] = '"'.implode('","',$title).'"';
        }
        if( !$data['title']['obj'] ){
            $title = array();
            foreach( $this->io_title('obj') as $k => $v )
                $title[] = $this->charset->utf2local($v);
            $data['title']['obj'] = '"'.implode('","',$title).'"';
        }
        $limit = 100;
        //if( $filter[''] )
        if( !$list=$this->getList('order_id',$filter,$offset*$limit,$limit) )return false;
        foreach( $list as $aFilter ){
            $aOrder = $this->dump($aFilter['order_id']);
            if( !$aOrder )continue;
            $objects = $this->db->select("SELECT * FROM sdb_ome_order_objects where order_id=".$aFilter['order_id']);
            if ($objects){
                foreach ($objects as $obj){
                    if ($service = kernel::service("ome.service.order.objtype.".strtolower($obj['obj_type']))){
                        $item_data = $service->process($obj);
                        if ($item_data)
                        foreach ($item_data as $itemv){
                            $orderObjRow = array();
                            $orderObjRow['*:订单号']   = $aOrder['order_bn'];
                            $orderObjRow['*:商品货号'] = $itemv['bn'];
                            $orderObjRow['*:商品名称'] = $itemv['name'];
                            $orderObjRow['*:购买单位'] = $itemv['unit'];
                            $orderObjRow['*:商品规格'] = $itemv['spec_info'] ? $itemv['spec_info']:"-";
                            $orderObjRow['*:购买数量'] = $itemv['nums'];
                            $orderObjRow['*:商品价格'] = $itemv['price'];

                            $data['content']['obj'][] = $this->charset->utf2local('="'.implode( '","', $orderObjRow ).'"');
                        }
                    }else {
                        $aOrder['order_items'] = $this->db->select("SELECT * FROM sdb_ome_order_items WHERE obj_id=".$obj['obj_id']." AND `delete`='false' AND order_id=".$aFilter['order_id']);
                        $aOrder['order_items'] = ome_order_func::add_items_colum($aOrder['order_items']);
                        $orderRow = array();
                        $orderObjRow = array();
                        $k = 0;
                        if ($aOrder['order_items'])
                        foreach( $aOrder['order_items'] as $itemk => $itemv ){
                            $orderObjRow = array();
                            $orderObjRow['*:订单号']   = $aOrder['order_bn'];
                            $orderObjRow['*:商品货号'] = $itemv['bn'];
                            $orderObjRow['*:商品名称'] = $itemv['name'];
                            $orderObjRow['*:购买单位'] = $itemv['unit'];
                            $orderObjRow['*:商品规格'] = $itemv['spec_info'] ? $itemv['spec_info']:"-";
                            $orderObjRow['*:购买数量'] = $itemv['nums'];
                            $orderObjRow['*:商品价格'] = $itemv['price'];

                            $data['content']['obj'][] = $this->charset->utf2local('="'.implode( '","', $orderObjRow ).'"');
                        }
                    }
                }
            }
            
            //处理地区数据
            $area = explode('/',$aOrder['consignee']['area'] );
            if(strpos($area[0],":")){
                $tmp_province = explode(":",$area[0]);
                $province = $tmp_province[1];
            }else{
                $province = $area[0];
            }
            $city = $area[1];
            if(strpos($area[2],":")){
                $tmp_county = explode(":",$area[2]);
                $county = $tmp_county[0];
            }else{
                $county = $area[2];
            }
            $aOrder['consignee']['area'] = array(
                'province' => $province,
                'city' => $city,
                'county' => $county,
            );

            $tmp_remark = kernel::single('ome_func')->format_memo($aOrder['custom_mark']);
            $tmp = '';
            if ($tmp_remark)
            foreach ($tmp_remark as $v){
                $tmp .= $v['op_content'].'-'.$v['op_time'].'-by-'.$v['op_name'].';';
            }
            $aOrder['custom_mark'] = $tmp;

            //处理店铺信息
            $shop = $this->app->model('shop')->dump($aOrder['shop_id']);
            $aOrder['shop_id'] = $shop['shop_bn'];
            $aOrder['createtime'] = date('Y-m-d H:i:s',$aOrder['createtime']);
            //处理订单优惠方案
            $order_pmtObj = $this->app->model('order_pmt');
            $pmt = $order_pmtObj->getList('pmt_describe',array('order_id'=>$aOrder['order_id']));
            foreach($pmt as $k=>$v){
                $pmt_tmp .= $v['pmt_describe'].";";
            }
            $aOrder['order_pmt']  = $pmt_tmp;

            foreach( $this->oSchema['csv']['order'] as $k => $v ){
                $orderRow[$k] = $this->charset->utf2local(utils::apath( $aOrder,explode('/',$v) ));
            }
            $data['content']['order'][] = '="'.implode('","',$orderRow).'"';
        }
        return true;
    }

    function export_csv($data,$exportType = 1 ){
        $output = array();
      //  if( $exportType == 2 ){
            foreach( $data['title'] as $k => $val ){
                $output[] = $val."\n".implode("\n",(array)$data['content'][$k]);
            }
      //  }
        echo implode("\n",$output);
    }

    function prepared_import_csv(){
        $this->ioObj->cacheTime = time();
    }

    function finish_import_csv(){
        $data = $this->import_data;
        unset($this->import_data);

        $orderTitle = array_flip( $this->io_title('order') );
        $objTitle = array_flip( $this->io_title('obj') );
        $orderSchema = $this->oSchema['csv']['order'];
        $objSchema =$this->oSchema['csv']['obj'];
        $oQueue = &app::get('base')->model('queue');

        $count = 0;
        $limit = 50;
        $page = 0;
        $orderSdfs = array();
        foreach( $data as $ordre_id => $aOrder ){
            $orderSdf = array();
            $orderSdf = $this->ioObj->csv2sdf( $aOrder['order']['contents'][0] ,$orderTitle,$orderSchema  );
            $orderObjectItem = 0;
            foreach( $aOrder['obj']['contents'] as $k => $v ){
                    $product_info = $this->app->model('products')->dump(array('bn'=>$v[$objTitle['*:商品货号']]));
                    if (!$product_info){
                        foreach(kernel::servicelist('ome.product') as $name=>$object){
                            if(method_exists($object, 'getProductInfoByBn')){
                                $product_data = $object->getProductInfoByBn($v[$objTitle['*:商品货号']]);
                                if($product_data){
                                    $orderSdf['order_objects'][$k]['bn']        = $v[$objTitle['*:商品货号']];
                                    $orderSdf['order_objects'][$k]['name']      = $v[$objTitle['*:商品名称']];
                                    $orderSdf['order_objects'][$k]['quantity']  = $v[$objTitle['*:购买数量']];
                                    $orderSdf['order_objects'][$k]['price']     = $v[$objTitle['*:商品价格']];
                                    $orderSdf['order_objects'][$k]['amount']    = $v[$objTitle['*:商品价格']]*$v[$objTitle['*:购买数量']];
                                    $orderSdf['order_objects'][$k]['obj_type']  = $product_data['product_type'];
                                    $orderSdf['order_objects'][$k]['obj_alias'] = $product_data['product_desc'];
                                    $orderSdf['order_objects'][$k]['goods_id']  = $product_data['goods_id'];
                                    if ($product_data['items']){
                                        $orderObjectItem = $k;
                                        foreach ($product_data['items'] as $inc => $iv){
                                            $orderSdf['order_objects'][ $orderObjectItem]['order_items'][$inc]['bn']          = $iv['bn'];
                                            $orderSdf['order_objects'][ $orderObjectItem]['order_items'][$inc]['name']        = $iv['name'];
                                            $orderSdf['order_objects'][ $orderObjectItem]['order_items'][$inc]['quantity']    = $iv['nums'] * $v[$objTitle['*:购买数量']];
                                            $orderSdf['order_objects'][ $orderObjectItem]['order_items'][$inc]['price']       = $iv['price']?$iv['price']:0;
                                            $orderSdf['order_objects'][ $orderObjectItem]['order_items'][$inc]['amount']      = $iv['nums'] * ($iv['price']?$iv['price']:0);
                                            $orderSdf['order_objects'][ $orderObjectItem]['order_items'][$inc]['obj_type']    = $product_data['product_type'];
                                            $orderSdf['order_objects'][ $orderObjectItem]['order_items'][$inc]['product_id']  = $iv['product_id'];
                                        }
                                    }else {
                                        $orderObjectItem = $k;
                                        $orderSdf['order_objects'][ $orderObjectItem]['order_items'][$k]['bn']          = $v[$objTitle['*:商品货号']];
                                        $orderSdf['order_objects'][ $orderObjectItem]['order_items'][$k]['name']        = $v[$objTitle['*:商品名称']];
                                        $orderSdf['order_objects'][ $orderObjectItem]['order_items'][$k]['quantity']    = $v[$objTitle['*:购买数量']];
                                        $orderSdf['order_objects'][ $orderObjectItem]['order_items'][$k]['price']       = $v[$objTitle['*:商品价格']];
                                        $orderSdf['order_objects'][ $orderObjectItem]['order_items'][$k]['amount']      = $v[$objTitle['*:商品价格']]*$v[$objTitle['*:购买数量']];
                                        $orderSdf['order_objects'][ $orderObjectItem]['order_items'][$k]['obj_type']    = $product_data['product_type'];
                                        $orderSdf['order_objects'][ $orderObjectItem]['order_items'][$k]['product_id']  = $product_data['product_id'];
                                    }
                                    break;
                                }
                            }
                        }
                    }else {
                        $orderSdf['order_objects'][$k]['bn'] = $v[$objTitle['*:商品货号']];
                        $orderSdf['order_objects'][$k]['name'] = $v[$objTitle['*:商品名称']];
                        $orderSdf['order_objects'][$k]['quantity'] = 1; //写死一个object一个item
                        $orderSdf['order_objects'][$k]['price']     = $v[$objTitle['*:商品价格']];
                        $orderSdf['order_objects'][$k]['amount'] = $v[$objTitle['*:商品价格']]*$v[$objTitle['*:购买数量']];
                        $orderSdf['order_objects'][$k]['obj_type'] = 'goods';   //写死一个object一个item，并且类型是goods
                        $orderSdf['order_objects'][$k]['obj_alias'] = '商品';    //写死一个object一个item，并且类型是商品
                        $orderSdf['order_objects'][$k]['goods_id'] = $product_info['goods_id'];

                        $orderObjectItem = $k;
                        $orderSdf['order_objects'][ $orderObjectItem]['order_items'][$k]['bn'] = $v[$objTitle['*:商品货号']];
                        $orderSdf['order_objects'][ $orderObjectItem]['order_items'][$k]['name'] = $v[$objTitle['*:商品名称']];
                        $orderSdf['order_objects'][ $orderObjectItem]['order_items'][$k]['quantity'] = $v[$objTitle['*:购买数量']];
                        $orderSdf['order_objects'][ $orderObjectItem]['order_items'][$k]['price'] = $v[$objTitle['*:商品价格']];
                        $orderSdf['order_objects'][ $orderObjectItem]['order_items'][$k]['amount'] = $v[$objTitle['*:商品价格']]*$v[$objTitle['*:购买数量']];
                        $orderSdf['order_objects'][ $orderObjectItem]['order_items'][$k]['obj_type'] = 'product';   //写死product
                        $orderSdf['order_objects'][ $orderObjectItem]['order_items'][$k]['product_id'] = $product_info['product_id'];
                    }

            }
            //处理店铺信息
            $shop = $this->app->model('shop')->dump(array('shop_bn'=>$orderSdf['shop_id']));
            $orderSdf['shop_id'] = $shop['shop_id'];
            $orderSdf['shop_type'] = $shop['shop_type'];
            $orderSdf['createtime'] = strtotime($orderSdf['createtime']);
            $orderSdf['consignee']['area'] = $orderSdf['consignee']['area']['province']."/".$orderSdf['consignee']['area']['city']."/".$orderSdf['consignee']['area']['county'];
            $orderSdf['shipping']['is_cod'] = $orderSdf['shipping']['is_cod']?strtolower($orderSdf['shipping']['is_cod']):'false';
            $orderSdf['is_tax'] = $orderSdf['is_tax']?strtolower($orderSdf['is_tax']):'false';
            $orderSdf['cost_tax'] = $orderSdf['cost_tax']?$orderSdf['cost_tax']:'0';
            $orderSdf['discount'] = $orderSdf['discount']?$orderSdf['discount']:'0';
            $orderSdf['score_g'] = $orderSdf['score_g']?$orderSdf['score_g']:'0';
            $orderSdf['cost_item'] = $orderSdf['cost_item']?$orderSdf['cost_item']:'0';
            $orderSdf['total_amount'] = $orderSdf['total_amount']?$orderSdf['total_amount']:'0';
            $orderSdf['pmt_order'] = $orderSdf['pmt_order']?$orderSdf['pmt_order']:'0';
            $orderSdf['pmt_goods'] = $orderSdf['pmt_goods']?$orderSdf['pmt_goods']:'0';
            $orderSdf['custom_mark'] = kernel::single('ome_func')->append_memo($orderSdf['custom_mark']);

            if($count < $limit){
                $count ++;
            }else{
                $count = 0;
                $page ++;
            }

            $orderSdfs[$page][] = $orderSdf;
        }

        foreach($orderSdfs as $v){
            $queueData = array(
                'queue_title'=>'订单导入',
                'start_time'=>time(),
                'params'=>array(
                    'sdfdata'=>$v,
                    'app' => 'ome',
                    'mdl' => 'orders'
                ),
                'worker'=>'ome_order_import.run',
            );
            $oQueue->save($queueData);

        }
        app::get('base')->model('queue')->flush();
    }

    //导入
    function prepared_import_csv_row($row,$title,&$tmpl,&$mark,&$newObjFlag,&$msg){
        if(empty($row)){
            $error_msg = array();
            if(isset($this->not_exist_product_bn)){
                if(count($this->not_exist_product_bn) > 10){
                    for($i=0;$i<10;$i++){
                        $not_exist_product_bn[] = current($this->not_exist_product_bn);
                        next($this->not_exist_product_bn);
                    }
                    $more = "...";
                }else{
                    $more = "";
                }
                $error_msg[] = "不存在的货号：".implode(",",$not_exist_product_bn).$more;
            }
            if(isset($this->duplicate_order_bn_in_file)){
                if(count($this->duplicate_order_bn_in_file) > 10){
                    for($i=0;$i<10;$i++){
                        $duplicate_order_bn_in_file[] = current($this->duplicate_order_bn_in_file);
                        next($this->duplicate_order_bn_in_file);
                    }
                    $more = "...";
                }else{
                    $more = "";
                }
                $error_msg[] = "文件中以下订单号重复：".implode(",",$this->duplicate_order_bn_in_file).$more;
            }
            if(isset($this->duplicate_order_bn_in_db)){
                if(count($this->duplicate_order_bn_in_db) > 10){
                    for($i=0;$i<10;$i++){
                        $duplicate_order_bn_in_db[] = current($this->duplicate_order_bn_in_db);
                        next($this->duplicate_order_bn_in_db);
                    }
                    $more = "...";
                }else{
                    $more = "";
                }
                $error_msg[] = "以下订单号在系统中已经存在：".implode(",",$this->duplicate_order_bn_in_db).$more;
            }
            if(!empty($error_msg)){
                unset($this->import_data);
                $msg['error'] = implode("     ",$error_msg);
                return false;
            }
        }


        $mark = false;
        $fileData = $this->import_data;
        if( !$fileData )
            $fileData = array();

        if( substr($row[0],0,1) == '*' ){
            $titleRs =  array_flip($row);

            $mark = 'title';

            return $titleRs;
        }else{
            if( $row[0] ){
                if( array_key_exists( '*:商品货号',$title )  ) {
                    if(!$this->app->model('products')->dump(array('bn'=>$row[1]))){
                        $product_status = false;
                        foreach(kernel::servicelist('ome.product') as $name=>$object){
                            if(method_exists($object, 'checkProductByBn')){
                                $product_info = $object->checkProductByBn($row[1]);
                                if($product_info){
                                    $product_status = true;
                                    break;
                                }
                            }
                        }
                        if ($product_status==false) $this->not_exist_product_bn = isset($this->not_exist_product_bn)?array_merge($this->not_exist_product_bn,array($row[1])):array($row[1]);
                    }

                    $fileData[$row[0]]['obj']['contents'][] = $row;
                }else{
                    //计数判断，是否超过10000条记录，超过就提示数据过多
                    if(isset($this->order_nums)){
						kernel::log($this->order_nums);
                        $this->order_nums ++;
                        if($this->order_nums > 5000){
                            unset($this->import_data);
                            $msg['error'] = "导入的数据量过大，请减少到5000单以下！";
                            return false;
                        }
                    }else{
                        $this->order_nums = 0;
                    }

                    if(isset($fileData[$row[0]])){
                        $this->duplicate_order_bn_in_file = isset($this->duplicate_order_bn_in_file)?array_merge($this->duplicate_order_bn_in_file,array($row[0])):array($row[0]);
                    }
                    if($this->dump(array('order_bn'=>$row[0]))){
                        $this->duplicate_order_bn_in_db = isset($this->duplicate_order_bn_in_db)?array_merge($this->duplicate_order_bn_in_db,array($row[0])):array($row[0]);
                    }
                    $fileData[$row[0]]['order']['contents'][] = $row;
                }

                $this->import_data = $fileData;
            }
        }


        return null;
    }

    function prepared_import_csv_obj($data,$mark,$tmpl,&$msg = ''){
        return null;
    }

    function counter_dispatch($filter=null){
        $table_name = app::get('ome')->model('orders')->table_name(1);
        $strWhere = '';

        $sql = 'SELECT count(*) as _count FROM `'.$this->table_name(1).'` WHERE '.$this->_filter($filter) . $strWhere;
        $row = $this->db->select($sql);

        return intval($row[0]['_count']);
    }

    function countAbnormal($filter=null){
        $abnormal_table_name = app::get('ome')->model('abnormal')->table_name(1);
        $strWhere = '';
        if(isset($filter['abnormal_type_id'])){
            $strWhere = ' AND '.$abnormal_table_name.'.abnormal_type_id ='.$filter['abnormal_type_id'];
        }

        $row = $this->db->select('SELECT count(*) as _count FROM `'.$this->table_name(1).'` LEFT JOIN  '.$abnormal_table_name.'  ON '.$this->table_name(1).'.order_id = '.$abnormal_table_name.'.order_id WHERE '.$this->_filter($filter) . $strWhere);

        return intval($row[0]['_count']);
    }

    function getlistAbnormal($cols='*', $filter=array(), $offset=0, $limit=-1, $orderType=null){
        if(!$cols){
            $cols = $this->defaultCols;
        }
        if(!empty($this->appendCols)){
            $cols.=','.$this->appendCols;
        }
        if($this->use_meta){
             $meta_info = $this->prepare_select($cols);
        }

        $abnormal_table_name = app::get('ome')->model('abnormal')->table_name(1);
        $strWhere = '';
        if(isset($filter['abnormal_type_id'])){
            $strWhere = ' AND '.$abnormal_table_name.'.abnormal_type_id ='.$filter['abnormal_type_id'];
        }

        $this->defaultOrder[0] = $this->table_name(true).'.createtime';
        $tmpCols = array();
        foreach(explode(',',$cols) as $col){
            if($col == 1){
                $tmpCols[] = $col;
            }else{
                $tmpCols[] = $this->table_name(true).'.'.$col;
            }
        }
        $cols = implode(',',$tmpCols);
        unset($tmpCols);

        $orderType = $orderType?$orderType:$this->defaultOrder;
        $sql = 'SELECT '.$cols.' FROM `'.$this->table_name(true).'` LEFT JOIN  '.$abnormal_table_name.'  ON '.$this->table_name(1).'.order_id = '.$abnormal_table_name.'.order_id WHERE '.$this->_filter($filter) . $strWhere;
        if($orderType)$sql.=' ORDER BY '.(is_array($orderType)?implode($orderType,' '):$orderType);

        $data = $this->db->selectLimit($sql,$limit,$offset);
        $this->tidy_data($data, $cols);
        if($this->use_meta && count($meta_info['metacols']) && $data){
            foreach($meta_info['metacols'] as $col){
                $obj_meta = new dbeav_meta($this->table_name(true),$col,$meta_info['has_pk']);
                $obj_meta->select($data);
            }
        }
        return $data;
    }

    function getColumns(){
        $columns = array();
        foreach( $this->_columns() as $k=>$v ){
            $columns[] = $k;
        }

        return $columns;
    }


    /**如果是订单编辑，保存订单的原始数据
     * @param int $log_id
     */
    function write_log_detail($log_id,$detail){
    	$ooObj = $this->app->model('operations_order');
    	$data = array(
    	   'log_id'=>$log_id,
    	   'order_id' => $detail['order_id'],
    	   'order_detail' =>$detail,
    	);
    	$ooObj->save($data);
    }

    /**
     * 读取订单编辑前的详情
     */
    function read_log_detail($order_id,$log_id){
    	$ooObj = $this->app->model('operations_order');
    	$oodetail = $ooObj->dump(array('order_id'=>$order_id,'log_id'=>$log_id),'*');
    	return $oodetail;
    }
    

    /**
     * 返回订单字段的对照表
     * @params string 状态
     * @params string key value
     *  刘向峰2012.12.13
     */
    public function trasform_status($type='status', $val)
    {
    	switch($type){
    		case 'status':
    			$tmpArr = array(
    			'active' => app::get('ome')->_('活动'),
    			'finish' => app::get('ome')->_('完成'),
    			'dead' => app::get('ome')->_('死单'),
    			);
    			return $tmpArr[$val];
    			break;
    		case 'pay_status':
    			$tmpArr = array(
    			0 => app::get('ome')->_('未付款'),
    			1 => app::get('ome')->_('已付款'),
    			2 => app::get('ome')->_('付款至担保方'),
    			3 => app::get('ome')->_('部分付款'),
    			4 => app::get('ome')->_('部分退款'),
    			5 => app::get('ome')->_('已退款'),
    			);
    			return $tmpArr[$val];
    			break;
    		case 'ship_status':
    			$tmpArr = array(
    			0 => app::get('ome')->_('未发货'),
    			1 => app::get('ome')->_('已发货'),
    			2 => app::get('ome')->_('部分发货'),
    			3 => app::get('ome')->_('部分退货'),
    			4 => app::get('ome')->_('已退货'),
    			);
    			return $tmpArr[$val];
    			break;
    	}
    }
     
}
?>